package com.lagou.demo;

import com.lagou.mapper.OrdersMapper;
import com.lagou.mapper.UserMapper;
import com.lagou.pojo.Order;
import com.lagou.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisAnnotationTest {

    private UserMapper userMapper;
    private OrdersMapper ordersMapper;
    private SqlSession sqlSession;

    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        sqlSession = sqlSessionFactory.openSession(true);
        userMapper = sqlSession.getMapper(UserMapper.class);
        ordersMapper = sqlSession.getMapper(OrdersMapper.class);
    }

    @After
    public void after() {
        sqlSession.close();
    }

    @Test
    public void add() {
        User user = new User();
        user.setId(4);
        user.setUsername("测试数据");
        user.setPassword("000");
        user.setBirthday("2022-01-01");
        userMapper.add(user);
    }
    @Test
    public void update() {
        User user = new User();
        user.setId(4);
        user.setUsername("测试数据修改");
        user.setPassword("abc");
        user.setBirthday("2022-12-12");
        userMapper.update(user);
    }
    @Test
    public void delete() throws IOException {
        userMapper.delete(4);
    }

    @Test
    public void findById() throws IOException {
        User user = userMapper.findById(1);
        System.out.println(user);
    }

    @Test
    public void findAll() {
        List<User> users = userMapper.findAll();
        users.forEach(user -> System.out.println(user));
    }

    @Test
    public void findAllOrdersAndUser() {
        // 一对一
        List<Order> orders = ordersMapper.findAllOrdersAndUserAnnotation();
        orders.forEach(order -> System.out.println(order));
    }

    @Test
    public void findAllUserToOrders() {
        // 一对多
        List<User> users = userMapper.findAllUserToOrders();
        users.forEach(user -> System.out.println(user));
    }

    @Test
    public void findAllUserToRole() {
        // 多对多
        List<User> users = userMapper.findAllUserToRole();
        users.forEach(user -> System.out.println(user));
    }


}
